package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Area;
import com.fanrenqiji.modules.sys.entity.Office;
import com.fanrenqiji.modules.sys.entity.Role;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.service.OfficeService;
import com.fanrenqiji.modules.sys.service.RoleService;
import com.fanrenqiji.modules.sys.service.SystemService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月5日 下午3:36:25
 * @description 角色Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/role")
public class RoleController extends BaseController {

    @Autowired
    private SystemService systemService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private RoleService roleService;

    @ModelAttribute("role")
    public Role get(@RequestParam(required = false) Long id) {
        if (id != null) {
            return systemService.getRole(id);
        } else {
            return new Role();
        }
    }

    /**
     * 查看角色列表
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = {"list", ""})
    public String list(Role role, Model model, HttpServletRequest request, HttpServletResponse response) {
        /*
         * Page<Role> page = roleService.find(new Page<Role>(request,
		 * response),role); model.addAttribute("page", page);
		 */
        List<Role> list = systemService.findAllRole();
        model.addAttribute("list", list);
        return "modules/sys/roleList";
    }

    /**
     * 查看角色列表
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "form")
    public String form(Role role, Model model) {
        User user = UserUtils.getUser();
        if (role.getOffice() == null) {
            role.setOffice(user.getOffice());
        }

        if (user.getCompany().getId() == role.getOffice().getId() || role.getOffice().getParentIds().contains("" + user.getCompany().getId() + ",")) {
            model.addAttribute("role", role);
            model.addAttribute("menuList", systemService.findAllMenu());
            model.addAttribute("officeList", officeService.findAll());
            return "modules/sys/roleForm";
        } else {
            model.addAttribute("role", role);
            model.addAttribute("menuList", systemService.findAllMenu());
            model.addAttribute("officeList", officeService.findAll());
            return "modules/sys/roleView";
        }
    }

    /**
     * 添加或跟新用户角色
     *
     * @param role               当前角色
     * @param model              消息验证model
     * @param oldName            角色名
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "save")
    public String save(Role role, Model model, String oldName, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, role)) {
            return form(role, model);
        }
        if (!"true".equals(checkName(oldName, role.getName()))) {
            addMessage(model, "保存角色'" + role.getName() + "'失败, 角色名已存在");
            return form(role, model);
        }
        systemService.saveRole(role);
        addMessage(redirectAttributes, "保存角色'" + role.getName() + "'成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/sys/role/?repage";
    }

    /**
     * 分配角色视图
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "assign")
    public String assign(Role role, Model model) {
        //这里获得了角色的用户
        User user = UserUtils.getUser();
        if(user.isAdmin()){
            model.addAttribute("users", role.getUserList());
        }else{
            model.addAttribute("users", systemService.findUserByRole(role));
        }
        return "modules/sys/roleAssign";
    }

    /**
     * 选取用户分配给角色
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "usertorole")
    public String selectUserToRole(Role role, Model model) {
        List<User> userList = role.getUserList();
        model.addAttribute("role", role);
        model.addAttribute("userList", userList);
        model.addAttribute("selectIds", role.getUserIds());
        model.addAttribute("officeList", officeService.findAll());
        return "modules/sys/selectUserToRole";
    }

    /**
     * 从角色中移除用户
     *
     * @param userId
     * @param roleId
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "outrole")
    public String outrole(Long userId, Long roleId, RedirectAttributes redirectAttributes) {
        Role role = systemService.getRole(roleId);
        User user = systemService.getUser(userId);
        if (user.equals(UserUtils.getUser())) {
            addMessage(redirectAttributes, "无法从角色【" + role.getName() + "】中移除用户【" + user.getName() + "】自己！");
        } else {
            Boolean flag = systemService.outUserInRole(role, userId);
            if (!flag) {
                addMessage(redirectAttributes, "用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除失败！");
            } else {
                addMessage(redirectAttributes, "用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除成功！");
            }
        }
        return "redirect:" + GlobalSetting.getAdminPath() + "/sys/role/assign?id=" + role.getId();
    }

    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "delete")
    public String delete(Long id, RedirectAttributes redirectAttributes) {
        roleService.delete(id);
        addMessage(redirectAttributes, "删除角色成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/sys/role/?repage";
    }

    /**
     * 为已有角色添加用户
     *
     * @param role               角色
     * @param idsArr             用户ids
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "assignrole")
    public String assignRole(Role role, Long[] idsArr, RedirectAttributes redirectAttributes) {
        StringBuilder msg = new StringBuilder();
        int newNum = 0;
        String message = "";

        //通过验证
        if (StringUtils.isBlank(validateOfficeBelowRole(role, idsArr))) {
            for (int i = 0; i < idsArr.length; i++) {
                //公司负责人角色每个机构只允许分配一个人
                if ("compPrincipal".equals(role.getEnName())) {
                    User user = systemService.getUser(idsArr[i]);
                    Long count = roleService.findByOfficeBelowRole("compPrincipal", user.getOffice().getId());
                    if (count > 0) {
                        addMessage(redirectAttributes, "[" + user.getOffice().getName() + "]机构下已经有人分配了[公司负责人]角色");
                        break;
                    }
                }
                User user = systemService.assignUserToRole(role, idsArr[i]);
                if (null != user) {
                    msg.append("<br/>新增用户【" + user.getName() + "】到角色【" + role.getName() + "】！");
                    newNum++;
                }
            }

            message = "已成功分配 " + newNum + " 个用户" + msg;
        } else {
            message = validateOfficeBelowRole(role, idsArr);
        }
        addMessage(redirectAttributes, message);
        return "redirect:" + GlobalSetting.getAdminPath() + "/sys/role/assign?id=" + role.getId();
    }


    public String validateOfficeBelowRole(Role role, Long[] idsArr) {
        String msg = "";
        for (int i = 0; i < idsArr.length; i++) {
            //公司负责人角色每个机构只允许分配一个人
            if ("compPrincipal".equals(role.getEnName())) {
                User user = systemService.getUser(idsArr[i]);
                List<Long> roleIds = user.getRoleIdList();
                if (!roleIds.contains(role.getId())) {
                    Long count = roleService.findByOfficeBelowRole("compPrincipal", user.getOffice().getId());
                    if (count > 0) {
                        msg = "[" + user.getOffice().getName() + "]机构下已经有人分配了[公司负责人]角色";
                        break;
                    }
                }

            }
        }
        return msg;

    }

    /**
     * 通过部门获得用户所在的部门
     *
     * @param officeId
     * @param response
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @ResponseBody
    @RequestMapping(value = "getUsers")
    public List<User> users(@RequestParam("officeId") Long officeId) {
        //可能会涉及到分页预留
        //Page<User> page = systemService.findUserByPage(new Page<User>(1, -1), user);
        List<User> users = systemService.findUserByOffice(new Office(officeId));
        return users;
    }

    /**
     * 校验角色名是否已经存在
     *
     * @param oldName
     * @param name
     * @return
     */
    @RequiresUser
    @ResponseBody
    @RequestMapping(value = "checkName")
    public String checkName(String oldName, String name) {
        if (name != null && name.equals(oldName)) {
            return "true";
        } else if (name != null && systemService.findRoleByName(name) == null) {
            return "true";
        }
        return "false";
    }
}
